# Python 3.9
import json
import requests
import sys
import base64
import sys
import hashlib

# 本程序是一个用于向企业微信群机器人推送内容的工具。

headers = {'Content-Type': 'application/json'}

def post_text(webhook_url,text_content,mention_phone=""):
    #推送存文本消息，第一个参数为webhook地址，第二个参数为文本内容，第三个参数为要@人的手机号码，多人需要使用逗号分开。
    if len(mention_phone)>0:
        payload_message = {"msgtype": "text","text": {"content": text_content,"mentioned_mobile_list":[mention_phone]}}
    else:
        payload_message = {"msgtype": "text","text": {"content": text_content}}
    response = requests.request("POST", webhook_url, headers=headers, data=json.dumps(payload_message))
    return response


def post_markdown(webhook_url,markdown_content):
    #推送Markdown内容，第一个参数为webhook地址，第二个参数为Markdown内容，第三个参数为要@人的手机号码，多人需要使用逗号分开。
    payload_message = {"msgtype": "markdown","markdown": {"content": markdown_content}} 
    response = requests.request("POST", webhook_url, headers=headers, data=json.dumps(payload_message))
    return response


def post_img(webhook_url,img_path):
    #推送本地图片内容，第一个参数为Webhook地址，第二个参数为本地图片的绝对路径。
    with open(img_path, 'rb') as f:
        img_data = f.read()
        img_base64 = base64.b64encode(img_data).decode()  #base64编码，需要加.decode() 转为字符串类型
        img_md5= hashlib.md5(img_data).hexdigest()  #计算MD5值
    payload_message = {"msgtype": "image","image": {"base64": img_base64,"md5": img_md5}}
    response = requests.request("POST", webhook_url, headers=headers, data=json.dumps(payload_message))
    return response


def post_file(webhook_url,file_path):
    #推送本地文件，第一个参数为Webhook地址，第一个参数为本地文件的路径。
    roobotkey = webhook_url.replace('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=','')
    upload_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key='+ roobotkey +'&type=file'
    file_data = {'file': open(file_path,'rb')}
    file_res = requests.post(upload_url, files=file_data)
    file_media_id = file_res.json()['media_id']
    payload_message = {"msgtype": "file","file": {"media_id": file_media_id}}
    response = requests.request("POST", webhook_url, headers=headers, data=json.dumps(payload_message))
    return response

if __name__ == '__main__':
    if len(sys.argv) > 1:
        post_markdown(sys.argv[1],sys.argv[2])